﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace zp.mk.cmdGUI
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker bgWorker = new BackgroundWorker();
        List<PingElement> pings = new List<PingElement>();

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnPing_Click(object sender, RoutedEventArgs e)
        {
            if (!bgWorker.IsBusy)
            {
                btnPing.IsEnabled = false;
                bgWorker.DoWork += bgWorker_DoWork;
                bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
                bgWorker.WorkerReportsProgress = true;
                bgWorker.ProgressChanged += bgWorker_ProgressChanged;
                bgWorker.RunWorkerAsync(new String[]{txtFrom.Text, txtTo.Text});
            }
        }

        bool first = true;
        void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lvOut.DataContext = pings;
            pgrBar.Value = e.ProgressPercentage;
        }

        void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //lvOut.DataContext = (List<PingElement>)e.Result;
            btnPing.IsEnabled = true;
            //lvOut.DataContext = pings;
        }

        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            String[] Args = (string[])e.Argument;
            sendPing(Args[0], Args[1]);
        }

        private void sendPing(String sFrom, String sTo)
        {
            List<String> IpAdresses = new List<string>();
            
            if (sTo != String.Empty)
            {
                string[] OctetsFrom = sFrom.Split('.');
                string[] OctetsTo = sTo.Split('.');
                int[] octets = new int[4];

                for (int i = Int32.Parse(OctetsFrom[0]); i <= Int32.Parse(OctetsTo[0]); i++)
                {
                    for (int j = Int32.Parse(OctetsFrom[1]); j <= Int32.Parse(OctetsTo[1]); j++)
                    {
                        for (int k = Int32.Parse(OctetsFrom[2]); k <= Int32.Parse(OctetsTo[2]); k++)
                        {
                            for (int l = Int32.Parse(OctetsFrom[3]); l <= Int32.Parse(OctetsTo[3]); l++)
                            {
                                string ip = i + "." + j + "." + k + "." + l;
                                if (!IpAdresses.Contains(ip))
                                {
                                    IpAdresses.Add(ip);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                IpAdresses.Add(sFrom);
            }

            foreach (String ip in IpAdresses)
            {
                string sArguments = "/C ping " + ip;
                Process p = new Process();
                p.StartInfo.FileName = "cmd";
                p.StartInfo.Arguments = sArguments;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();

                p.WaitForExit();

                string output = p.StandardOutput.ReadToEnd();

                string sent = output.Substring(output.IndexOf("Gesendet") + 11, 2);
                if (sent.Contains(',')) sent = sent.Substring(0, 1);

                string lost = output.Substring(output.IndexOf("Verloren") + 11, 2);
                if (lost.Contains('\r')) lost = lost.Substring(0, 1);

                string lat = output.Substring(output.IndexOf("Mittelwert") + 13, 3);
                if (lat.Contains("ms")) lat = lat.Substring(0, 1);
                if (lat.Contains('m')) lat = lat.Substring(0, 2);

                PingElement pe = new PingElement();
                pe.Ip = ip;
                pe.PakSent = Int32.Parse(sent);
                pe.PakLost = Int32.Parse(lost);
                pe.AvgLat = Int32.Parse(lat);

                pings.Add(pe);
                double index = IpAdresses.IndexOf(ip)+1;
                double percent = index / IpAdresses.Count * 100;
                bgWorker.ReportProgress((int)percent);
            }
            

            //return pings;
        }

    }
}
